/*
 * @Author       : wfl
 * @LastEditors: wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-03-02 09:54:41
 * @LastEditTime: 2023-04-18 11:45:20
 */
import type { AxiosRequestConfig } from 'axios'
import type { ApiModel } from '@g/types/global'
import api from '.'

const controller = new AbortController()
const defaultConfig = {
  signal: controller.signal
}
/**
 * @description:
 * @param {string} url
 * @param {any} data
 * @param {AxiosRequestConfig} config: {
  // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  responseType: 'json', // 默认值

  // `xsrfCookieName` 是 xsrf token 的值，被用作 cookie 的名称
  xsrfCookieName: 'XSRF-TOKEN', // 默认值
  // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值

  // `onUploadProgress` 允许为上传处理进度事件
  onUploadProgress: function (progressEvent) {
    // 处理原生进度事件
  },
  // `onDownloadProgress` 允许为下载处理进度事件
  onDownloadProgress: function (progressEvent) {
    // 处理原生进度事件
  },

  cancelToken: new CancelToken(function (cancel) {
  })
 * }
 * @return {*}
 */
const post = async (url: string, data: any = {}, config: AxiosRequestConfig = defaultConfig): Promise<ApiModel> => await api.post(url, data, {
  ...config
})

const get = async (url: string, params: any = {}, config: AxiosRequestConfig = defaultConfig): Promise<ApiModel> => await api.get(url, {
  params,
  ...config
})

const put = async (url: string, data: any = {}, config: AxiosRequestConfig = defaultConfig): Promise<ApiModel> => await api.put(url, data, {
  ...config
})

const del = async (url: string, params: any = {}, config: AxiosRequestConfig = defaultConfig): Promise<ApiModel> => await api.delete(url, {
  params,
  ...config
})

const delData = async (url: string, data: any = {}, config: AxiosRequestConfig = defaultConfig): Promise<ApiModel> => await api.delete(url, {
  data,
  ...config
})

const patch = async (url: string, data: any = {}, config: AxiosRequestConfig = defaultConfig): Promise<ApiModel> => await api.patch(url, {
  data,
  ...config
})

const netPostFile = async (
  url: string,
  param: object,
  fileNameStr: string
) => {
  const apiUrl = `${/^http(s)?:\/{2}?/.test(url) ? url : url}`
  try {
    const res = await api({
      method: 'post',
      url: apiUrl,
      data: param
    })
    const blob = new Blob([res.data]) // application/vnd.ms-excel这里表示xls类型文件
    const contentDisposition = res.headers['content-disposition'] // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    const patt = /filename=([^;]+\.[^\.;]+);*/
    const result = patt.exec(contentDisposition)
    const filename = result ? result[1] : fileNameStr
    const downloadElement = document.createElement('a')
    const href = window.URL.createObjectURL(blob) // 创建下载的链接
    const reg = /^["](.*)["]$/g
    downloadElement.style.display = 'none'
    downloadElement.href = href
    downloadElement.download = decodeURI(filename.replace(reg, '$1')) // 下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() // 点击下载
    document.body.removeChild(downloadElement) // 下载完成移除元素
    window.URL.revokeObjectURL(href) // 释放掉blob对象
    return res
  }
  catch (err) {
    console.info('ERROE', err)
  }
}

export const ikHttp = {
  post,
  get,
  put,
  del,
  delData,
  patch,
  netPostFile,
  // 取消请求
  cancle: () => controller.abort()
}

export const textHeader = {
  headers: { 'Content-Type': 'text/plain' }
}
